package com.amdox.liugui.springbooteasyexcel.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.amdox.liugui.springbooteasyexcel.component.CellRowHeightStyleStrategy;
import com.amdox.liugui.springbooteasyexcel.component.CellStyleStrategy;
import com.amdox.liugui.springbooteasyexcel.component.CellWidthStyleStrategy;
import com.amdox.liugui.springbooteasyexcel.pojo.User;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExcelUtil {
    /**
     * 生成临时excel文件 并写入符合格式的数据 带固定样式表头
     * @param args
     */
    public static void main(String[] args) {
        String targetPathName = "相对路径" + File.separator + System.currentTimeMillis();
        String headName = "demo".concat(StrUtil.SPACE).concat("特殊要求");
        String fileName = headName + ".xls";
        File targetPath = new File(targetPathName);
        targetPath.mkdirs();
        File file = new File(targetPath, fileName);
        ExcelUtil.noModelWrite(headName, file, new ArrayList<User>());

        // 删除临时文件
        FileUtils.delete(new File(targetPathName));
    }

    public static void noModelWrite(String headName, File file, List<User> dataList) {
        // 表头
        List<List<String>> head = head(headName);
        //主标题和副标题在excel中分别是是第0和第1行
        List<Integer> columnIndexes = Arrays.asList(0, 1);

        EasyExcel.write(file)
                .head(head)
                .registerWriteHandler(new CellWidthStyleStrategy())// 设置列宽策略
                .registerWriteHandler(new CellRowHeightStyleStrategy())   //设置行高策略
                .registerWriteHandler(new CellStyleStrategy(columnIndexes, new WriteCellStyle(), new WriteCellStyle()))        //设置表头和内容的策略
                .sheet("Data")
                .doWrite(dataList());
    }


    private static List<List<String>> head(String name){
         return new ArrayList<>();
    }


    /*********** test code ***********/

    public static void noModelWriteTest(String customerNo, String specModel) {
        List<List<String>> head = head(specModel);
        String fileName = customerNo + specModel + System.currentTimeMillis() + ".xls";
        EasyExcel.write(fileName)
                .head(head)
                .sheet("模板")
                .doWrite(dataList());
    }

    private static List<List<Object>> dataList() {
        List<List<Object>> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            List<Object> data = ListUtils.newArrayList();
            data.add("字符串" + i);
            data.add(0.56);
            list.add(data);
        }
        return list;
    }
}
